package com.xxlie.spring.controller;

import com.xxlie.spring.annotation.Log;
import com.xxlie.spring.common.Constants;
import com.xxlie.spring.common.UserContext;
import com.xxlie.spring.common.View;
import com.xxlie.spring.entity.OperateLog;
import com.xxlie.spring.entity.User;
import com.xxlie.spring.service.OperateLogService;
import com.xxlie.spring.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

@Slf4j
@Controller
public class IndexController {

    @Autowired
    private UserService userService;

    @Autowired
    private OperateLogService operateLogService;

    @RequestMapping(value = "/")
    public ModelAndView index() {
        log.info("进入首页.");
        List<OperateLog> operateLogList = operateLogService.getOperateLogList();
        ModelAndView modelAndView = new ModelAndView("index");
        modelAndView.addObject("operateLogList", operateLogList);
        return modelAndView;
    }

    @RequestMapping(value = "/goRegister")
    public String goRegister() {
        return "register";
    }

    @ResponseBody
    @RequestMapping(value = "/register")
    @Log(module = "首页", method = "用户注册")
    public View<User> doRegister(@RequestParam String name, @RequestParam String passwd) {
        return View.ofOk(userService.doRegister(name, passwd));
    }

    @RequestMapping(value = "/goLogin")
    public String goLogin() {
        return "login";
    }

    @ResponseBody
    @RequestMapping(value = "/login")
    @Log(module = "首页", method = "用户登录")
    public View<User> doLogin(@RequestParam String name, @RequestParam String passwd, HttpServletRequest request) {
        User user = userService.doLogin(name, passwd);
        HttpSession session = request.getSession();
        session.setAttribute(Constants.USER_SESSION_KEY, user);
        return View.ofOk(user);
    }

}
